package xyz.heyaoshare.config.satoken.utils;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import xyz.heyaoshare.core.entity.system.User;
import xyz.heyaoshare.core.mapper.system.UserMapper;

import static xyz.heyaoshare.exceptions.code.ErrorInfo.INVALID_TOKEN;
import static xyz.heyaoshare.exceptions.customize.ServerException.exception;

/**
 * 认证工具类
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 上午11:54
 */
@Slf4j
@Component
public class AuthUtils {

    @Resource
    private UserMapper userMapper;

    /**
     * 获取当前用户的用户ID
     *
     * @return 当前用户的用户ID
     * @throws xyz.heyaoshare.exceptions.customize.ServerException 当登录信息错误或格式不正确时抛出异常
     */
    public Long getUserId() {
        Object loginId = StpUtil.getLoginId();
        if (loginId != null) {
            try {
                return Long.parseLong(loginId.toString());
            } catch (NumberFormatException e) {
                log.error("登录信息错误:{}", loginId, e);
                throw exception(INVALID_TOKEN);
            }
        }
        log.error("登录信息错误:loginId为null");
        throw exception(INVALID_TOKEN);
    }

    /**
     * 在不进行权限检查的情况下获取当前登录用户的用户ID
     *
     * @return 当前登录用户的用户ID，如果用户未登录或发生异常则返回null
     */
    public Long getUserIdNoCheck() {
        try {
            return StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            return null;
        }
    }

    public User getUser() {
        Long loginId = getUserId();
        return userMapper.selectOneById(loginId);
    }
}